﻿using System.Windows;
using System.Windows.Controls;
using AvalonDock;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using RiskMan.DataClass.Models;
using System.Collections.ObjectModel;
using RiskMan.Views.Dialogs;
using RiskMan.Properties;
using System.Reflection;
using System.Text.RegularExpressions;

namespace RiskMan.Config
{
    /// <summary>
    /// Логика взаимодействия для UserControl1.xaml
    /// </summary>
    public partial class MainSettings : DocumentContent
    {
        private MainWindow mainWindow;

        public MainSettings()
        {
            try
            {
                this.mainWindow = RiskMan.MainWindow.StaticRiskMan;
                InitializeComponent();

                TextBox_CPDayCliring.Text = Settings.Default.CPDayCliringValue.ToString();
                TextBox_CPNightCliring.Text = Settings.Default.CPNightCliringValue.ToString();
                TextBox_CPSession.Text = Settings.Default.CPSessionValue.ToString();
                //txbxBlockCapital.Text = Settings.Default.BlockPercentsCapital.ToString();

                checkBox1.IsChecked = Settings.Default.IsWorkCPDayCliring;
                checkBox2.IsChecked = Settings.Default.IsWorkCPNightCliring;
                checkBox3.IsChecked = Settings.Default.IsWorkCPSession;

                StartSessionHH.Text = RiskMan.Properties.Settings.Default.StartSessionHH.ToString();
                StartSessionMM.Text = RiskMan.Properties.Settings.Default.StartSessionMM.ToString();
                StopSessionHH.Text = RiskMan.Properties.Settings.Default.StopSessionHH.ToString();
                StopSessionMM.Text = RiskMan.Properties.Settings.Default.StopSessionMM.ToString();
                StopSessionFortsHH.Text = RiskMan.Properties.Settings.Default.StopSessionFortsHH.ToString();
                StopSessionFortsMM.Text = RiskMan.Properties.Settings.Default.StopSessionFortsMM.ToString();
                TextBox_Commis.Text = RiskMan.Properties.Settings.Default.Commis.ToString();

                dataGrid1.ItemsSource = mainWindow._dataProvider.MmvbComisList;
                DataGrid_QuikItems.ItemsSource = mainWindow._dataProvider.T2QItems;

                //if (RiskMan.Properties.Settings.Default.BlockSeccode != "")
                //{
                //    ComboBox_BlockFortsSeccode.ItemsSource = new List<String>()
                //    {
                //        cfg.UNKNOWN,
                //        RiskMan.Properties.Settings.Default.BlockSeccode
                //    };
                //    ComboBox_BlockFortsSeccode.SelectedIndex = 1;
                //}

                //if (RiskMan.Properties.Settings.Default.BlockSeccodeMMVB != "")
                //{
                //    ComboBox_BlockMmvbSeccode.ItemsSource = new List<String>()
                //    {
                //        cfg.UNKNOWN,
                //        RiskMan.Properties.Settings.Default.BlockSeccodeMMVB
                //    };
                //    ComboBox_BlockMmvbSeccode.SelectedIndex = 1;
                //}

                TextBox_HHdk.Text = Properties.Settings.Default.StartDay.Hour.ToString();
                TextBox_MMdk.Text = Properties.Settings.Default.StartDay.Minute.ToString();

                TextBox_HHnk.Text = Properties.Settings.Default.StartNight.Hour.ToString();
                TextBox_MMnk.Text = Properties.Settings.Default.StartNight.Minute.ToString();


                TimeSpan ts = Properties.Settings.Default.EndDay.Subtract(Properties.Settings.Default.StartDay);
                TextBox_Idk.Text = ts.TotalMinutes + "";

                ts = Properties.Settings.Default.EndNight.Subtract(Properties.Settings.Default.StartNight);
                TextBox_Ink.Text = ts.TotalMinutes + "";

                if (Settings.Default.TypeCloseOrderBlocking == "MarketCloseOrderBlocking")
                    rbtnMarketCloseOrderBlocking.IsChecked = true;
                else
                    rbtnLimitCloseOrderBlocking.IsChecked = true;
                txbxCloseOrderLimit.Text = Settings.Default.PercentsForTypeCloseOrderLimit.ToString();

            }
            catch (Exception ex)
            {
                cfg.SetLog(ex.Message, MainWindow.StaticRiskMan.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }



        //private void СomboBox_BlockSeccode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    try
        //    {
        //        if (ComboBox_BlockFortsSeccode.SelectedValue != null)
        //        {
        //            if (ComboBox_BlockFortsSeccode.SelectedValue.ToString() == cfg.UNKNOWN)
        //                new DialogOkCancel("Для блокировки не подходит \'" + cfg.UNKNOWN + "\'", "Ошибка");

        //            RiskMan.Properties.Settings.Default.BlockSeccode = ComboBox_BlockFortsSeccode.SelectedValue.ToString();
        //            RiskMan.Properties.Settings.Default.Save();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        cfg.SetLog(ex.ToString(), mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        //    }
        //}

        private List<String> GetListSeccode()
        {
            List<String> result = new List<string>() { cfg.Unknown };

            for (int i = 0; i < mainWindow._dataProvider.CurrentList.Count; i++)
                result.Add(mainWindow._dataProvider.CurrentList[i].Seccode);

            return result;
        }

        //private void Button_Load_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        ComboBox_BlockMmvbSeccode.ItemsSource = this.GetListSeccode();

        //        ComboBox_BlockFortsSeccode.ItemsSource = this.GetListSeccode();
        //    }
        //    catch (Exception ex)
        //    {
        //        cfg.SetLog(ex.Message, MainWindow.StaticRiskMan.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        //    }
        //}

        private void textBox3_TextChanged(object sender, TextChangedEventArgs e)
        {
            double price = cfg.ToDoubleFormControls(((System.Windows.Controls.TextBox)sender).Text.ToString());

            RiskMan.Properties.Settings.Default.Commis = price;
            RiskMan.Properties.Settings.Default.Save();
        }

        /// <summary>
        /// Показывает окно добавления нового Quik
        /// </summary>
        /// <param name="sender">Button</param>
        /// <param name="e"></param>
        private void Button_Add_Click(object sender, RoutedEventArgs e)
        {
            newQuikView nqv = new newQuikView(false, new QuikItem() { TradeList = new ObservableCollection<Trade>() }, mainWindow._dataProvider);
            nqv.ShowDialog();

            if (nqv.tmpQuik != null)
                mainWindow._dataProvider.T2QItems.Add((QuikItem)cfg.DeepClone(new QuikItem()
                {
                    Name = nqv.tmpQuik.Name,
                    Path = nqv.tmpQuik.Path,
                    TradeList = nqv.tmpQuik.TradeList,
                    Comments = nqv.tmpQuik.Comments
                }));

            DataGrid_QuikItems.IsReadOnly = false;
            DataGrid_QuikItems.ItemsSource = mainWindow._dataProvider.T2QItems;
            DataGrid_QuikItems.Items.Refresh();
            DataGrid_QuikItems.IsReadOnly = true;
        }

        private void button_Del_Click(object sender, RoutedEventArgs e)
        {
            if (DataGrid_QuikItems.SelectedIndex >= 0)
            {


                DataGrid_QuikItems.IsReadOnly = false;
                DataGrid_QuikItems.ItemsSource = mainWindow._dataProvider.T2QItems;
                DataGrid_QuikItems.Items.Refresh();
                DataGrid_QuikItems.IsReadOnly = true;
            }
            else
            {
                new DialogOkCancel("Выберите какой-нибудь из Quik", "Ошибка");
            }
        }

        /// <summary>
        /// Выводит информацию для редактирован ия
        /// </summary>
        /// <param name="sender">DataGrid</param>
        /// <param name="e"></param>
        private void DataGrid_QuikItems_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid).SelectedItems.Count == 1)
            {
                newQuikView nqv = new newQuikView(true, ((System.Windows.Controls.DataGrid)sender).SelectedItem as QuikItem, mainWindow._dataProvider);
                nqv.ShowDialog();

                if (nqv.tmpQuik != null)
                {
                    mainWindow._dataProvider.T2QItems[((System.Windows.Controls.DataGrid)sender).SelectedIndex] = new QuikItem()
                        {
                            Name = nqv.tmpQuik.Name,
                            Path = nqv.tmpQuik.Path,
                            Comments = nqv.tmpQuik.Comments,
                            TradeList = nqv.tmpQuik.TradeList
                        };
                }
                DataGrid_QuikItems.ItemsSource = mainWindow._dataProvider.T2QItems;
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.StartDay = new DateTime(DateTime.Now.Year,
                                                                DateTime.Now.Month,
                                                                DateTime.Now.Day,
                                                                Convert.ToInt32(TextBox_HHdk.Text),
                                                                Convert.ToInt32(TextBox_MMdk.Text), 0);
            DateTime endday = Properties.Settings.Default.StartDay;
            double inter = Convert.ToDouble(TextBox_Idk.Text);
            DateTime temp = endday.AddMinutes(inter);

            Properties.Settings.Default.EndDay = temp;

            Properties.Settings.Default.StartNight = new DateTime(DateTime.Now.Year,
                                                                DateTime.Now.Month,
                                                                DateTime.Now.Day,
                                                                Convert.ToInt32(TextBox_HHnk.Text),
                                                                Convert.ToInt32(TextBox_MMnk.Text), 0);
            DateTime endnight = new DateTime(DateTime.Now.Year,
                                           DateTime.Now.Month,
                                           DateTime.Now.Day,
                                           Convert.ToInt32(TextBox_HHnk.Text),
                                           Convert.ToInt32(TextBox_MMnk.Text), 0);
            inter = Convert.ToDouble(TextBox_Ink.Text);
            temp = endnight.AddMinutes(inter);
            Properties.Settings.Default.EndNight = temp;

            Properties.Settings.Default.Save();

            mainWindow.startNight = Properties.Settings.Default.StartNight;
            mainWindow.endNight = Properties.Settings.Default.EndNight;
        }

        #region Копирование строки

        private void DataGrid_QuikItems_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid).SelectedItems.Count == 1)
            {
                int index = (sender as System.Windows.Controls.DataGrid).SelectedIndex + 1;
                DataGrid_QuikItems.UnselectAll();
                if (new DialogYesNo("Вы действительно хотите скопировать строку " + index + "?", "Внимаение").Result == MessageBoxResult.Yes)
                {
                    var tmp = (QuikItem)cfg.DeepClone(mainWindow._dataProvider.T2QItems[index - 1 < 0 ? 0 : index - 1]);

                    string s = tmp.Name;
                    for (int j = 0; j < 10; j++)
                    {
                        bool tr = false;
                        for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                            if (mainWindow._dataProvider.T2QItems[i].Name == s)
                            {
                                s += "0";
                                j = 0;
                                tr = true;
                                break;
                            }
                        if (tr == false)
                            break;
                    }
                    tmp.Name = s;
                    mainWindow._dataProvider.T2QItems.Add(tmp);
                }
            }
            else
            {

            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (DataGrid_QuikItems.SelectedItems.Count == 1)
            {
                int index = DataGrid_QuikItems.SelectedIndex + 1;
                DataGrid_QuikItems.UnselectAll();
                if (new DialogYesNo("Вы действительно хотите скопировать строку " + index + "?", "Внимаение").Result == MessageBoxResult.Yes)
                {
                    var tmp = (QuikItem)cfg.DeepClone(mainWindow._dataProvider.T2QItems[index - 1 < 0 ? 0 : index - 1]);

                    string s = tmp.Name;
                    for (int j = 0; j < 10; j++)
                    {
                        bool tr = false;
                        for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                            if (mainWindow._dataProvider.T2QItems[i].Name == s)
                            {
                                s += "0";
                                j = 0;
                                tr = true;
                                break;
                            }
                        if (tr == false)
                            break;
                    }
                    tmp.Name = s;
                    mainWindow._dataProvider.T2QItems.Add(tmp);
                }
            }
            else
            {

            }
        }

        #endregion

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (DataGrid_QuikItems.SelectedItems.Count == 1)
            {
                mainWindow._dataProvider.T2QItems.RemoveAt(DataGrid_QuikItems.SelectedIndex);
            }
            DataGrid_QuikItems.ItemsSource = mainWindow._dataProvider.T2QItems;
        }

        private void TextBox_HHdk_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void TextBox_Commis_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.Commis = cfg.ToDoubleFormControls(TextBox_Commis.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StartSessionHH_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StartSessionHH = (int)cfg.ToDoubleFormControls(StartSessionHH.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StartSessionMM_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StartSessionMM = (int)cfg.ToDoubleFormControls(StartSessionMM.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StopSessionHH_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StopSessionHH = (int)cfg.ToDoubleFormControls(StopSessionHH.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StopSessionMM_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StopSessionMM = (int)cfg.ToDoubleFormControls(StopSessionMM.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StopSessionFortsMM_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StopSessionFortsMM = (int)cfg.ToDoubleFormControls(StopSessionFortsMM.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void StopSessionFortsHH_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.StopSessionFortsHH = (int)cfg.ToDoubleFormControls(StopSessionFortsHH.Text);
            RiskMan.Properties.Settings.Default.Save();
        }

        private void Button_ComisDel_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItems.Count == 1)
            {
                mainWindow._dataProvider.MmvbComisList.RemoveAt(dataGrid1.SelectedIndex);
                dataGrid1.ItemsSource = mainWindow._dataProvider.MmvbComisList;
            }

            dataGrid1.UnselectAll();
        }

        private void Button_ComisAdd_Click(object sender, RoutedEventArgs e)
        {
            ComisView tmp = new ComisView() { Topmost = true };
            tmp.ShowDialog();

            if (tmp.Item != null)
            {
                mainWindow._dataProvider.MmvbComisList.Add(tmp.Item);
                dataGrid1.ItemsSource = mainWindow._dataProvider.MmvbComisList;
            }

            dataGrid1.UnselectAll();
        }

        //private void ComboBox_BlockMmvbSeccode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    try
        //    {
        //        if (ComboBox_BlockMmvbSeccode.SelectedValue != null)
        //        {
        //            if (ComboBox_BlockMmvbSeccode.SelectedValue.ToString() == cfg.UNKNOWN)
        //                new DialogOkCancel("Для блокировки не подходит  \'" + cfg.UNKNOWN + "\'", "Ошибка");

        //            RiskMan.Properties.Settings.Default.BlockSeccodeMMVB = ComboBox_BlockMmvbSeccode.SelectedValue.ToString();
        //            RiskMan.Properties.Settings.Default.Save();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        cfg.SetLog(ex.Message, MainWindow.StaticRiskMan.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        //    }
        //}

        private void TextBox_CPDayCliring_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.CPDayCliringValue = cfg.ToDoubleFormControls(TextBox_CPDayCliring.Text);
            SaveProperty();
        }

        private void TextBox_CPNightCliring_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.CPNightCliringValue = cfg.ToDoubleFormControls(TextBox_CPNightCliring.Text);
            SaveProperty();
        }

        private void TextBox_CPSession_TextChanged(object sender, TextChangedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.CPSessionValue = cfg.ToDoubleFormControls(TextBox_CPSession.Text);
            SaveProperty();
        }

        private void checkBox1_Click(object sender, RoutedEventArgs e)
        {
            if (checkBox1.IsChecked == false)
                RiskMan.Properties.Settings.Default.IsWorkCPDayCliring = false;
            else
                RiskMan.Properties.Settings.Default.IsWorkCPDayCliring = true;

            SaveProperty();
        }

        private void checkBox2_Click(object sender, RoutedEventArgs e)
        {
            if (checkBox2.IsChecked == false)
                RiskMan.Properties.Settings.Default.IsWorkCPNightCliring = false;
            else
                RiskMan.Properties.Settings.Default.IsWorkCPNightCliring = true;

            SaveProperty();
        }

        private void checkBox3_Click(object sender, RoutedEventArgs e)
        {
            if (checkBox3.IsChecked == false)
                RiskMan.Properties.Settings.Default.IsWorkCPSession = false;
            else
                RiskMan.Properties.Settings.Default.IsWorkCPSession = true;

            SaveProperty();
        }

        private void SaveProperty()
        {
            RiskMan.Properties.Settings.Default.Save();
        }

        //private void txbxBlockCapital_TextChanged(object sender, TextChangedEventArgs e)
        //{
        //    try
        //    {
        //        Settings.Default.BlockPercentsCapital = Convert.ToDouble(txbxBlockCapital.Text.ToString());

        //    }
        //    catch (Exception)
        //    {

        //    }
        //    if (Settings.Default.BlockPercentsCapital > 100 || Settings.Default.BlockPercentsCapital < 0)
        //        Settings.Default.BlockPercentsCapital = 100;

        //    Settings.Default.Save();
        //}

        private void txbxBlockCapital_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

        }

        //private void txbxBlockCapital_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        //{
        //    e.Handled = "0123456789 ,".IndexOf(e.Text) < 0;
        //    if (txbxBlockCapital.Text.IndexOf(',') == 1 && e.Text == ",")
        //        e.Handled = true;



        //}

        private void rbtnMarketCloseOrderBlocking_Checked(object sender, RoutedEventArgs e)
        {
            Settings.Default.TypeCloseOrderBlocking = "MarketCloseOrderBlocking";
            Settings.Default.Save();
        }

        private void rbtnLimitCloseOrderBlocking_Checked(object sender, RoutedEventArgs e)
        {
            Settings.Default.TypeCloseOrderBlocking = "LimitCloseOrderBlocking";
            Settings.Default.Save();
        }

        private void txbxCloseOrderLimit_TextChanged(object sender, TextChangedEventArgs e)
        {
            Settings.Default.PercentsForTypeCloseOrderLimit = Convert.ToDouble(txbxCloseOrderLimit.Text);
            Settings.Default.Save();
        }
    }
}